package com.taobaostore.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taobaostore.common.ServerResponse;
import com.taobaostore.service.IFileService;
import com.taobaostore.util.FTPUtil;
@Service
public class FileServiceImpl implements IFileService{
	/**
	 * 上传文件
	 */
    public ServerResponse<String> upload(MultipartFile file,String path) {
    	String fileName = file.getOriginalFilename();
    	// 获取文件拓展名
    	String fileExtensionName = fileName.substring(fileName.indexOf(".")+1);
    	// 拼接上传文件名
    	String fileUploadName = UUID.randomUUID().toString()+ "." + fileExtensionName;
    	File fileDir = new File(path);
    	if (!fileDir.exists()) {
			fileDir.setWritable(true);
			fileDir.mkdir();
		}
    	// 得到要上傳的目標文件
    	File targetFile = new File(path,fileUploadName);
    	try {
			file.transferTo(targetFile);
			//TODO 将文件上传至FTP图片服务器
			FTPUtil.fileUpload(fileUploadName, file.getInputStream());
            //TODO 将本机tomcat磁盘下的图片删除
			fileDir.delete();
    	} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    	return ServerResponse.createBySuccess("上传成功",fileUploadName);
    }
}
